package com.smartrobot.smartrobot.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.adapter.PosSelectAdapter;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageUtil;
import com.smartrobot.smartrobot.util.PictureFromCammera;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/12/22.
 */
public class ActiveSendActivity extends Activity implements View.OnClickListener {


    private ImageView back,addPic;
    private ImageView addSomethig;
    private TextView sharePos,progress,send_active_txt;
    private RelativeLayout send;
    private EditText shareTxt;
    private Map<String, String> map;

    //上传图片保存路径
    private String path = null;

    //dialog
    private ListView dialogListView;

    private List<Integer> mSharePosSelect;
    private boolean isSendActive = false;
    private ActiveSendHandler handler ;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
        this.setContentView(R.layout.page_friend_active_send);


        init();

    }

    void init(){

        HttpUtil.init(getApplicationContext());
        initView();
    }

    void initView(){

        back = (ImageView)findViewById(R.id.send_active_back);
        addSomethig = (ImageView)findViewById(R.id.active_send_add_something);
        addPic = (ImageView)findViewById(R.id.active_send_add_pic);
        sharePos = (TextView)findViewById(R.id.send_active_sharePos);
        send = (RelativeLayout)findViewById(R.id.send_active_send);
        shareTxt = (EditText)findViewById(R.id.active_send_editext);
        progress = (TextView)findViewById(R.id.active_send_add_progess);
        send_active_txt = (TextView)findViewById(R.id.send_active_txt);

        back.setOnClickListener(this);
        addSomethig.setOnClickListener(this);
        addPic.setOnClickListener(this);
        sharePos.setOnClickListener(this);
        send.setOnClickListener(this);


        mSharePosSelect = new ArrayList<Integer>();
        mSharePosSelect.add(this.getIntent().getIntExtra("pos",0));//设置默认分享地方

    }

    @Override
    public void onClick(View view) {

        switch(view.getId()) {

            case R.id.send_active_back:

                if(isSendActive) {
                    ToastCustom.showToast(getApplicationContext(),"正在发布动态中，请稍后...");
                }
                else
                ActiveSendActivity.this.finish();

                break;

            case R.id.active_send_add_something:
            case R.id.active_send_add_pic:
                 //用dilog显示获得图片的路径
                AlertDialog dialog = new AlertDialog.Builder(ActiveSendActivity.this)
                        .setTitle("选择")
                        .setItems(R.array.photoMenu,
                                new AlertDialog.OnClickListener() {

                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        switch (which) {
                                            case 0://通过照相机获取图片
                                                path = ImageUtil.getCameraPic(ActiveSendActivity.this, ImageUtil.IMAGE_FROM_CAMMERA);
                                                break;
                                            case 1://通过打开文件获取图片
                                                ImageUtil.getDirPic(ActiveSendActivity.this, ImageUtil.IMAGE_FROM_FILE);
                                                break;
                                        }
                                    }
                                }).show();

                    dialog.setCanceledOnTouchOutside(true);

                break;

            case R.id.send_active_sharePos:


                // Get the layout inflater
                LayoutInflater inflater = this.getLayoutInflater();
                View dialogView = inflater.inflate(R.layout.dialog_select_pos, null);

                PosSelectAdapter adapter = new PosSelectAdapter(this, mSharePosSelect);
                dialogListView = (ListView) dialogView.findViewById(R.id.dialog_select_pos_listView);
                dialogListView.setAdapter(adapter);

                AlertDialog dialog1 = new AlertDialog.Builder(this).setView(dialogView).show();
                dialog1.setCanceledOnTouchOutside(true);

                break;

            case R.id.send_active_send:  //发送动态
                switch (legal()) {
                    case 0:
                        ToastCustom.showToast(getApplicationContext(), "没有分享到的地方");
                        break;

                    case 1:
                        ToastCustom.showToast(getApplicationContext(), "请填写内容");
                        break;

                    case 2:
                        ToastCustom.showToast(getApplicationContext(), "字数不超过1000");
                        break;

                    default:
                        if (!isSendActive) {


                            map = new HashMap<String, String>();
                            map.put("content", shareTxt.getText().toString());
                            if (addSomethig.getVisibility() == View.VISIBLE) {
                                map.put("shareType", "");
                            } else {
                                map.put("shareType", "图片");//图片
                            }
                            map.put("file", path);
                            //向我的圈子和全世界发送消息
                            if (mSharePosSelect.size() == 2)
                                map.put("sharePos", "2");
                            else
                                map.put("sharePos", "" + mSharePosSelect.get(0));


                            handler = new ActiveSendHandler();
                            HttpUtil.apiSendActive(map, handler);
                            send_active_txt.setText("正在发布");
                            isSendActive = true;
                        }else{
                            ToastCustom.showToast(getApplicationContext(),"正在发布动态中，请稍后...");
                        }
                        break;
                }
        }
    }

    //判断是否可以具备必要条件发送动态
    int legal(){

        if(mSharePosSelect.size() == 0) return 0;
        if(shareTxt.getText().toString().length() == 0) return 1;
        if(shareTxt.getText().toString().length() > 1000) return 2;

        return 10;
    }

    // 处理返回结果
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == ImageUtil.IMAGE_FROM_CAMMERA) {// 通过照相机获取图片
            if (resultCode == RESULT_OK) { // 成功获得图片
                if(path != null && !path.equals(""))
                {
                    Bitmap addBitmap = PictureFromCammera.scaleBitmap(path);

                    // 头像的名字
                    String fileName = FileUtil.tempAddPic;
                    //保存的路径
                    String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
                            + fileName;


                    if (FileUtil.createFile(filePath)) {
                        // 将图片保存在文件夹中
                        if (FileUtil.writeBitmapToSDCard(filePath,addBitmap))
                        {
                            addSomethig.setVisibility(View.GONE);
                            addPic.setImageBitmap(addBitmap);
                            addPic.setVisibility(View.VISIBLE);
                            progress.setVisibility(View.VISIBLE);
                            path = filePath;
                        }
                    }

                }
                else
                    ToastCustom.showToast(getApplicationContext(), "无法获取图片，请重新选择");


            }
        }

        if (requestCode == ImageUtil.IMAGE_FROM_FILE) {//打开文件夹获取图片
            if (resultCode == RESULT_OK) { // 成功
                try {
                    Uri uri=data.getData();
                    Cursor cursor=getContentResolver().query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    path=cursor.getString(1);
                    cursor.close();
                    if(path != null){
                        Bitmap addBitmap = PictureFromCammera.scaleBitmap(path);
                        String fileName = FileUtil.tempAddPic;
                        String filePath = FileUtil.PHONE_DIR_INNER + FileUtil.PICTURE
                                + fileName;


                        if (FileUtil.createFile(filePath)) {
                            // 保存到手机sd卡中，同时缩小图片大小
                            if (FileUtil.writeBitmapToSDCard(filePath,addBitmap))
                            {
                                addSomethig.setVisibility(View.GONE);
                                addPic.setImageBitmap(addBitmap);
                                addPic.setVisibility(View.VISIBLE);
                                progress.setVisibility(View.VISIBLE);
                                path = filePath;
                            }
                        }
                    }
                    else
                        ToastCustom.showToast(getApplicationContext(), "无法保存图片，请重新选择");
                } catch (Exception e)
                {
                    ToastCustom.showToast(getApplicationContext(), "无法找到图片，请重新选择");
                }
            }
        }
    }

    class ActiveSendHandler extends Handler {

        @Override
        public void dispatchMessage(Message msg) {


            switch (msg.what){

                case HttpUtil.SEND_ACTIVE_SUCCESS:

//                    isSendActive = false;

                    //发送成功后结束activity
                    //返回操作数据 返回成功
                    Intent intent = new Intent();
                    if(mSharePosSelect.size() == 2 && mSharePosSelect.contains(1) && mSharePosSelect.contains(0))
                        intent.putExtra("size",2);
                    else
                    intent.putExtra("size",1);
                    intent.putExtra("pos",mSharePosSelect.get(0));
                    setResult(RESULT_OK,intent);
                    ToastCustom.showToast(getApplicationContext(),"发送成功");
                    ActiveSendActivity.this.finish();

                    break;

                case HttpUtil.SEND_ACTIVE_FAILD:

                    if(msg.obj.toString().equals("100")){//未登录,帮助用户登录

                        HttpUtil.reLogin(getApplicationContext(),handler);
                        //这里有一个问题是：是否需要在发布一次动态

                    }else {

                        ToastCustom.showToast(getApplicationContext(),"无法发送");

                    }
                    isSendActive = false;
                    send_active_txt.setText("发布");
                    break;

                case HttpUtil.SEND_ACTIVE_PROGRESS:

                    if(msg.arg1 == 100)
                        progress.setVisibility(View.GONE);
                    else{
                        progress.setVisibility(View.VISIBLE);
                        progress.setText( msg.arg1 + "%");
                    }


                    break;

                case HttpUtil.LOGIN_SUCCESS:

                    HttpUtil.apiSendActive(map, handler);

                    break;

                case HttpUtil.LOGIN_FAILD:

                    isSendActive = false;
                    send_active_txt.setText("发布");
                    ToastCustom.showToast(getApplicationContext(),"请重新登录...");

                    break;


            }


        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK){

            if(isSendActive) {
                ToastCustom.showToast(getApplicationContext(),"正在发布动态中，请稍后...");
                return false;
            }

        }

        return super.onKeyDown(keyCode, event);
    }
}